package cn.wb.search.service.impl;

import cn.wb.base.service.impl.BaseServiceImpl;
import cn.wb.base.util.*;
import cn.wb.order.domain.OrderPetAcquisition;
import cn.wb.order.dto.AcceptDto;
import cn.wb.order.mapper.OrderPetAcquisitionMapper;
import cn.wb.org.domain.Shop;
import cn.wb.org.mapper.ShopMapper;
import cn.wb.pet.domain.Pet;
import cn.wb.pet.mapper.PetMapper;
import cn.wb.search.domain.SearchMasterMsg;
import cn.wb.search.domain.SearchMasterMsgAuditLog;
import cn.wb.search.dto.SearchMasterMsgDto;
import cn.wb.search.mapper.SearchMasterMsgAuditLogMapper;
import cn.wb.search.mapper.SearchMasterMsgMapper;
import cn.wb.search.service.ISearchMasterMsgService;
import cn.wb.user.domain.Logininfo;
import cn.wb.user.domain.User;
import cn.wb.user.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author itsource
 * @since 2023-01-10
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper auditLogMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private SearchMasterMsgMapper msgMapper;
    @Autowired
    private PetMapper petMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderMapper;

    /**
     * 发布寻主
     * @param dto
     * @return
     */
    @Override
    public AjaxResult publish(SearchMasterMsgDto dto) {
        // 参数校验
        // 1.保存数据
        SearchMasterMsg masterMsg = new SearchMasterMsg();
        BeanUtils.copyProperties(dto,masterMsg);
        // 设置状态
        masterMsg.setState(0);
        // 设置userId 当心 空指针
        Logininfo logininfo = LoginContext.getUserInfo().getLogininfo();
        // 通过logininfo的id查询userid
        User user = userMapper.findByLoginInfoId(logininfo.getId());
        masterMsg.setUserId(user.getId());
        super.add(masterMsg);
        // 2.百度AI审核
        if (!BaiduAuditUtils.TextCensor(dto.getName())){
            // 审核不通过 添加日志
            SearchMasterMsgAuditLog auditLog = new SearchMasterMsgAuditLog();
            auditLog.setMsgId(masterMsg.getId());
            auditLog.setAuditTime(new Date());
            auditLog.setNote("宠物名称审核不通过！"+dto.getName());
            auditLog.setAuditId(-1L);
            auditLog.setState(0);
            // 添加审核日志
            auditLogMapper.add(auditLog);
            // msg的状态改成 审核失败
            masterMsg.setState(2);

        }else {
            // 审核通过
            // 3.找店铺
            Point point = DistanceUtil.getPoint(dto.getAddress());
            List<Shop> shopList = shopMapper.findAll();
            Shop nearestShop = DistanceUtil.getNearestShop(point, shopList);
            if (null != nearestShop){
                // 找到了店铺 我们应该干什么？
                masterMsg.setShopId(nearestShop.getId());
            }

            // msg的状态改成 审核通过
            masterMsg.setState(1);
        }
        // 4.最后 更新店铺状态
        super.update(masterMsg);

        return AjaxResult.me().success();
    }

    /**
     * 拒单
     * @param id
     */
    @Override
    public void reject(Long id) {
        // 把当前消息 的shopId改成null
        msgMapper.reject(id);

    }

    /**
     * 接单
     * @param dto
     */
    @Override
    public void accept(AcceptDto dto) {

        // 参数校验

        // 0.根据msgId查询数据
        SearchMasterMsg msg = msgMapper.findById(dto.getMsgId());

        // 1.生成收购单信息
        OrderPetAcquisition order = getOrder(dto, msg); // 现在的order 缺少一个petID

        // 2.生成宠物信息
        Pet pet = getPet(msg);

        // 3.修改msg的状态为 已接单
        msg.setState(3);
        msgMapper.update(msg);
        // 添加宠物信息
        petMapper.add(pet);
        // 添加order
        order.setPetId(pet.getId());
        orderMapper.add(order);
    }


    public Pet getPet(SearchMasterMsg msg){
        return Pet
                .builder()
                .name(msg.getName())
                .costprice(BigDecimal.valueOf(msg.getPrice()))
                .state(0)
                .typeId(msg.getPetType())
                .createtime(new Date())
                .shopId(msg.getShopId())
                .searchMasterMsgId(msg.getId())
                .build();
    }

    public OrderPetAcquisition getOrder(AcceptDto dto,SearchMasterMsg msg) {
        return OrderPetAcquisition
                .builder()
                .orderSn(CodeGenerateUtils.generateOrderSn(msg.getUserId()))
                .digest(dto.getNote())
                .lastConfirmTime(new Date(System.currentTimeMillis()+2*24*60*60*1000))
                .state(0)
                .price(BigDecimal.valueOf(msg.getPrice()))
                .payType(1)
                .paySn("12121212")
                .userId(msg.getUserId())
                .shopId(msg.getShopId())
                .address(msg.getAddress())
                .empId(dto.getHandler())
                .msgId(msg.getId())
                .build();
    }
}
